import re

# from typing import List, Dict, Any
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser, JsonOutputParser
from langchain_openai import ChatOpenAI
import os
import sys

# from dotenv import load_dotenv, find_dotenv
os.environ["http_proxy"] = "http://127.0.0.1:10808"
os.environ["https_proxy"] = "http://127.0.0.1:10808"

OPENAI_API_KEY = "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"

TRANSLATION_EVALUATION_PROMPT = """
根据给出的原文和学生的翻译答案，详细评估翻译的质量。请考虑以下方面：
原文：{original_text}
翻译：{student_answer}
这是一个对于学生翻译的评分示例：
学生原文 ： 据说这一地区早在两千年前农业就很先进。
待翻译内容： This is a test.
{{
    "accuracy": {{
        "score": 0,
        "reason": "翻译内容与原文完全无关，没有传达原文的任何信息，因此准确性得分为零。"
    }},
    "fluency": {{
        "score": 0,
        "reason": "虽然'This is a test.'在英语中语法和流畅性都正确，但由于内容与原文无关，流畅性评分也极低。"
    }},
    "grammar": {{
        "score": 0,
        "reason": "提供的英语句子从语法角度看是正确的，但由于内容与原文无关，语法评分低。"
    }}
}}
您的评估需要基于翻译的准确性、流畅性和语法正确性。请使用以下JSON格式输出您的评分和评价理由：
{{
    "accuracy": {{
        "score": [满分 10 分],
        "reason": "对翻译准确性的具体评价，例如是否忠实原文，信息是否传达完整等"
    }},
    "fluency": {{
        "score": [满分 10 分],
        "reason": "对翻译流畅性的具体评价，如读起来是否自然流畅，是否符合目标语言的习惯等"
    }},
    "grammar": {{
        "score": [满分 10 分],
        "reason": "对翻译的语法正确性的具体评价，包括语法错误、拼写错误及标点使用等"
    }}
    "detailed_suggestions": 
    "基于作者的英语能力提供针对性的改进建议，旨在帮助提高翻译水平。建议可以包括具体的翻译技巧、语法改进点、词汇使用建议等"
}}
请确保您的反馈既详尽又具体，帮助了解翻译的优点和需要改进的地方。
"""


def evaluate_translation(student_answer: str, original_text: str, question_score: int):
    """
    这个函数评估学生的翻译答案，并提供对答案的分析。

    参数:
    student_answer (str): 学生的翻译答案。
    original_text (str): 原始文本。
    question_score (int): 问题的分数。

    返回:
    dict: 包含评估成功状态、数据（包括总分和各项得分及原因）以及在评估过程中出现的任何错误的字典。
    """
    try:
        prompt_template = ChatPromptTemplate.from_template(
            TRANSLATION_EVALUATION_PROMPT
        )
        llm = ChatOpenAI(openai_api_key=OPENAI_API_KEY)
        json_parser = JsonOutputParser()
        # 定义输出解析规则
        chain = prompt_template | llm | json_parser

        evaluation_result = chain.invoke(
            {"student_answer": student_answer, "original_text": original_text}
        )
        # print(evaluation_result)
        # 计算总分
        total_score = (
            evaluation_result["accuracy"]["score"] * 0.4
            + evaluation_result["fluency"]["score"] * 0.3
            + evaluation_result["grammar"]["score"] * 0.3
        )
        total_score = total_score * question_score / 10
        data = {
            "totalScore": int(total_score),
            "accuracyScore": evaluation_result["accuracy"]["score"],
            "accuracyComment": evaluation_result["accuracy"]["reason"],
            "fluencyScore": evaluation_result["fluency"]["score"],
            "fluencyComment": evaluation_result["fluency"]["reason"],
            "syntaxScore": evaluation_result["grammar"]["score"],
            "syntaxComment": evaluation_result["grammar"]["reason"],
            "detailedSuggestions": evaluation_result["detailed_suggestions"],
        }
        print(str(data))
    except Exception as e:
        print(e)
        # return {"success": False, "data": None, "error": str(e)}


if __name__ == "__main__":

    student_answer = sys.argv[1]
    original_text = sys.argv[2]
    question_score = int(sys.argv[3])
    # student_answer = "\r\n\r\nTranslation:\r\nNear my home, there is a beautiful park where I often take walks. The park is filled with tall trees, colorful flowers, and a clear stream. Every time I enter the park, I feel the fresh air, as if leaving all worries behind. I enjoy strolling in the park, admiring the beauty of nature, and listening to the birds' songs. Sometimes, I find a quiet corner, sit down, and read a book or contemplate life. The park is a great place for me to relax and free my mind. Every time I leave the park, I feel refreshed and energized."
    # student_answer = "woshizhendebuhui"
    # original_text = "我家附近有一个美丽的公园，我经常在那里散步。公园里有高大的树木，五彩斑斓的花朵，还有清澈的小溪。每当我走进公园，都会感受到一股清新的空气，仿佛所有的烦恼都被抛在了身后。我喜欢在公园里漫步，欣赏大自然的美丽，聆听鸟儿的歌唱。有时，我会找一个安静的角落，坐下来读书或者思考人生。公园是我放松心情，放飞思绪的好地方。每次离开公园，我都感到心情舒畅，充满了活力。"
    # question_score = 10
    evaluate_translation(student_answer, original_text, question_score)
